package com.blb.eduuserservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.common.entity.Student;
import com.blb.common.util.HttpClientUtils;
import com.blb.eduuserservice.config.WXConfigurationProperties;
import com.blb.eduuserservice.service.StudentService;
import com.blb.eduuserservice.service.WxLoginService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Service
public class WxLoginServiceImpl implements WxLoginService {

    //用于获得access-token的url
    public static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    //用户获得用户信息的url
    public static final String URL_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

    @Resource
    private WXConfigurationProperties wxConfigurationProperties;

    @Resource
    private StudentService studentService;

    @Override
    public Student wxLogin(String code) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        //传入授权码，向微信平台获得access-token
        String urlToken = String.format(URL_ACCESS_TOKEN, wxConfigurationProperties.getAppId(), wxConfigurationProperties.getAppSecret(), code);
        String result = HttpClientUtils.get(urlToken);
        //将返回的数据解析出access-token,openid
        Map<String,String> map = objectMapper.readValue(result, Map.class);
        String accessToken = map.get("access_token");
        String openid = map.get("openid");
        log.info("access-token:{}",map);
        //判断该微信用户是否登录过系统
        Student one = studentService.getOne(new QueryWrapper<Student>().lambda().eq(Student::getOpenid, openid));
        if(one == null){
            //使用access-token+openid获得用户的信息
            String urlUserinfo = String.format(URL_USER_INFO, accessToken, openid);
            result = HttpClientUtils.get(urlUserinfo);
            map = objectMapper.readValue(result, Map.class);
            //获得用户昵称和头像
            String nickname = map.get("nickname");
            String icon = map.get("headimgurl");
            log.info("userinfo:{}",map);
            //保存用户信息到本地数据库
            Student student = new Student();
            student.setNickname(nickname);
            student.setOpenid(openid);
            student.setIcon(icon);
            studentService.register(student);
            return student;
        }
        return one;
    }
}
